<template>
	<view class="page-cont" :style="themeStore.theme">
		<navbar :title="projectName" type="1" :selectList="projectList" selectKey="name"
			@selectChange="handleProjectChange"></navbar>
		<view class="main-cont" :style="{height: pageHeight}">
			<!-- tab栏 -->
			<tab :tabActive="tabActive" :tabs="tabs" :badges="badges" @tabChange="handleTabChange"></tab>
			<!-- 预警信息 -->
			<view class="notice-bar" v-if="alarmList.length>0">
				<image class="notice-icon" src="/static/procject_warning.png"></image>
				<swiper class="notice-swiper" vertical="true" autoplay="true" circular="true" interval="3000"
					duration="500" :disable-touch="true">
					<swiper-item v-for="(item, index) in alarmList" :key="index" @tap="toAlarm(item)">
						<view class="notice-item">{{ item.title }}</view>
					</swiper-item>
				</swiper>
			</view>
			<!-- 设备列表 -->
			<scroll-view class="scroll-cont" scroll-y refresher-enabled :refresher-triggered="isRefresh"
				@refresherrefresh="handlePullDownRefresh">
				<device-cold v-if="projectType == 20" :alarmList="alarmList"></device-cold>
				<device-compressor v-if="projectType == 40" :alarmList="alarmList"></device-compressor>
				<device-condenser v-if="projectType == 30" :alarmList="alarmList"></device-condenser>
			</scroll-view>
			<!-- 菜单栏 -->
			<image class="menu-btn" src="/static/project-menu.png" @click="handleDrawer"></image>
		</view>
		<uni-drawer ref="drawerMenu" mode="right" :mask-click="true">
			<menuBar></menuBar>
		</uni-drawer>
	</view>
</template>
<script setup lang="ts">
	import { reactive, ref, watch } from 'vue';
	import { onShow, onLoad, onUnload } from "@dcloudio/uni-app";
	import { storeToRefs } from 'pinia';
	import { useNavbar } from "@/utils/hooks.js";
	import { getProjectList, getProjectModel, getProjectMonitor, getProjectAlarm } from "@/api/home.js";
	import { getPMMTAlerts } from "@/api/warn.js";
	import menuBar from "@/components/menu.vue";
	import DeviceCold from "./components/device-cold.vue";
	import DeviceCompressor from "./components/device-compressor.vue";
	import DeviceCondenser from "./components/device-condenser.vue";
	import useHomeStore from '@/store/home';
	import useThemeStore from '@/store/theme';
	const themeStore = useThemeStore();
	const homeStore = useHomeStore();
	const { pageHeight } = useNavbar();
	const { projectId, projectName, projectType, deviceList } = storeToRefs(homeStore);
	const tabs = ref([]);
	const tabList = ref([])
	const badges = ref([])
	const tabActive = ref(-1)
	const projectList = ref([])
	const alarmList = ref([])
	const modusData = ref({})
	const popup = ref()
	const drawerMenu = ref()
	const isRefresh = ref(false)
	const warnInfoList = ref([])

	// const isFirst = ref(true)
	onLoad(() => {
		getProjectData();
		initData();
	});

	onUnload(() => {
		homeStore.clearProjectData();
	});

	// onShow(() => {
	// 	// console.log('tabActive', tabActive.value)
	// 	// getProjectData();
	// 	// initData();
	// })

	async function initData() {
		await getModelData();
		await getAlarmData();
		// await getPMMTAlert();
		isRefresh.value = false;
	}


	// 告警通知
	function getPMMTAlert() {
		getPMMTAlerts({ mid: projectId.value }).then(res => {

		});
	}


	// 获取全部项目
	function getProjectData() {
		getProjectList({ isAll: true }).then(res => {
			projectList.value = res.data || [];
			homeStore.setProjectList(res.data || []);//保存项目列表
		});
	}

	// 获取项目的模块数据
	function getModelData() {
		return new Promise(resolve => {
			if (!projectId.value) {
				resolve(false);
				return;
			}
			getProjectModel({ pmid: projectId.value }).then(res => {
				modusData.value = res.modus || {};
				homeStore.setProjectModus(res.modus || {});//保存项目模块

				tabList.value = [];
				let keys = Object.keys(modusData.value);
				if (keys.indexOf("20") !== -1 && modusData.value["20"].length) {
					// 20 冷间
					tabList.value.push({ name: "冷间", id: 20 });
				}
				if (keys.indexOf("40") !== -1 && modusData.value["40"].length) {
					// 40 机组
					tabList.value.push({ name: "机组", id: 40 });
				}
				if (keys.indexOf("30") !== -1 && modusData.value["30"].length) {
					// 30 冷凝器
					tabList.value.push({ name: "冷凝器", id: 30 });
				}
				if (tabList.value.length) {
					tabActive.value = 0;
					let type = tabList.value[0].id;
					homeStore.setProjectType(type);//保存项目类型
				}
				console.log('tabActive', tabActive.value)
				console.log('ProjectType', projectType.value)
				tabs.value = tabList.value.map(element => {
					return element.name;
				});

				console.log('tabActive', tabActive.value)
				resolve(true);
			});
		});
	}

	// 获取项目的告警数据
	function getAlarmData() {
		return new Promise(resolve => {
			if (!projectId.value) {
				resolve(false);
				return;
			}
			getProjectAlarm({ mid: projectId.value }).then(res => {
				// if (res.data) {
				// 	alarmList.value = (res.data || {})["ad"];
				// 	console.log("alarmList.value ", alarmList.value)
				// }
				alarmList.value = res.ad;
				resolve(true);
			});
		});
	}

	// 获取设备数据
	function getList() {
		let arr = [];

		deviceList.value.forEach(element => {
			if (element.confmapping instanceof String) {
				element.confmapping = JSON.parse(element.confmapping || "");
			} else {
				element.confmapping = element.confmapping;
			}
			arr.push(element.datamapping[0]);
		});
		if (!arr.length) {
			return;
		}
		getProjectMonitor({ keys: arr }).then(res => {
			// 获取预警设备的id
			let alarmIds = alarmList.value.map(element => {
				return element.oid;
			});
			deviceList.value.forEach(element => {
				let key = element.datamapping;
				let confmapping = element.confmapping;
				let min = Number(confmapping.min);//下限
				let max = Number(confmapping.max);//上限
				element.num = Number(res[key] || 0);
				// 判断当前设备是否超标
				if (element.num < min || element.num > max) {
					// 不在上下限范围
					element.warn = true;
				} else {
					element.warn = false;
				}
				// 判断当前设备是否预警
				if (alarmIds.indexOf(element.id) !== -1) {
					element.alarm = true;
				} else {
					element.alarm = false;
				}
			});
		});
	}

	// 下拉刷新
	const handlePullDownRefresh = () => {
		isRefresh.value = true;
		initData();
	}

	// 下拉选择项目
	function handleOpen() {
		popup.value.open();
	}

	// 项目切换
	function handleProjectChange(item) {
		homeStore.setProjectType(0);
		homeStore.setProjectId(item.id);//保存项目id
		homeStore.setProjectName(item.name);//保存项目名称
		initData();
		// handleTabChange(0);
		// homeStore.setProjectType(tabList.value[tabActive.value].id);

	}

	// 项目类型切换
	async function handleTabChange(e) {
		console.log("handleTabChange ", e)
		tabActive.value = e;
		let type = tabList.value[tabActive.value].id;
		let list = modusData.value[type];
		if (type == 20) {
			let child = modusData.value["21"];
			list.forEach(item1 => {
				child.forEach(item2 => {
					if (item1.id == item2.pid) {
						item1.datamapping = JSON.parse(item2.datamapping);
					}
				});
			});
		}
		homeStore.setProjectType(type);//保存项目类型
		homeStore.setDeviceList(list);//保存设备列表
		getList();
	}

	// 菜单栏
	function handleDrawer() {
		drawerMenu.value.open();
	}

	// 详情
	function handleDetailClick(e) {
		homeStore.setDeviceId(e.id);//保存设备id
		homeStore.setDeviceName(e.name);//保存设备名称
		uni.navigateTo({
			url: `/pages/home/coldroom`,
		});
	}

	function toAlarm(e) {
		uni.navigateTo({
			url: `/pages/warn/list`,
		});
	}
</script>
<style lang="scss" scoped>
	.page-cont {
		position: relative;

		.main-cont {
			position: relative;
		}

		.menu-btn {
			position: fixed;
			right: 25px;
			bottom: 37px;
			width: 50px;
			height: 50px;
		}

		.scroll-cont {
			height: calc(100% - 40px);
		}


		.device-list {
			margin-top: 5px;
			padding: 0 15px 15px;
			display: flex;
			flex-wrap: wrap;
			box-sizing: border-box;

			.device-item {
				margin-left: 15px;
				padding: 10px;
				width: calc(50% - 8px);
				border-radius: 5px;
				background: linear-gradient(180deg, rgba(238, 240, 249, 1), #fff);
				border: 1px solid #fff;
				box-shadow: 0px 10px 20px 0px rgba(95, 131, 249, 0.1);
				box-sizing: border-box;

				&:nth-child(2n + 1) {
					margin-left: 0;
				}

				&:nth-child(n + 3) {
					margin-top: 15px;
				}

				&.device-item-alarm {
					border-color: #FC4A2E;
					background: linear-gradient(180deg, #F9F1F0, #fff);
				}
			}

			.device-item-top {
				position: relative;
				display: flex;

				.device-item-top-icon {
					width: 40px;
					height: 40px;
				}

				.device-item-limit {
					margin-left: 10px;
					width: calc(100% - 50px);
				}

				.device-item-limit-name,
				.device-item-limit-value {
					color: #8A95A0;
					font-size: 11px;
					word-break: break-all;
				}

				.device-item-limit-value {
					margin-top: 5px;
				}

				.device-item-status {
					position: absolute;
					top: 0;
					right: 0;
					width: 8px;
					height: 8px;
					border-radius: 4px;
					background-color: #75E0A8;

					&.device-item-status-alarm {
						background-color: #FC4A2E;
					}
				}
			}

			.device-item-name {
				margin-top: 7px;
				color: #333;
				font-size: 13px;
				font-weight: 600;
			}

			.device-item-bottom {
				margin-top: 15px;
				display: flex;
				justify-content: space-between;
				align-items: flex-end;

				.device-item-temp-num {
					color: $theme-color;
					font-size: 22px;
					font-weight: 600;

					&.device-item-temp-warn {
						color: #FC4A2E;
					}
				}

				.device-item-temp-name {
					padding: 0 10px;
					height: 20px;
					display: flex;
					align-items: center;
					color: #878F96;
					font-size: 13px;
					border-radius: 10px;
					border: 1px solid #FFFFFF;
					box-shadow: 0px 0px 10px 0px rgba(95, 131, 249, 0.2);
					background: linear-gradient(180deg, rgba(236, 239, 247, 1), rgba(255, 255, 255, 1));
				}

				.device-item-temp-icon {
					margin-left: 7px;
					width: 12px;
					height: 11px;
				}

				.device-item-arrow {
					width: 15px;
					height: 14px;
				}
			}
		}

		.notice-bar {
			display: flex;
			align-items: center;
			padding: 20rpx 25rpx;
			background-color: rgba(255, 140, 0, 0.2);
			border-radius: 10rpx;
			box-shadow: 0 2rpx 10rpx rgba(0, 0, 0, 0.1);

			.notice-icon {
				width: 33rpx;
				height: 33rpx;
				margin-right: 15rpx;
			}

			.notice-swiper {
				flex: 1;
				height: 40rpx;
			}

			.notice-item {
				font-size: 26rpx;
				color: #FF8C00;
				line-height: 40rpx;
				/* 单行显示，超出省略 */
				white-space: nowrap;
				overflow: hidden;
				text-overflow: ellipsis;
			}
		}

	}
</style>